<?php
class Answer_Component_Controller_Admincp_Category extends Phpfox_Component {
    public function process() {
		
        $sLink = "admincp.answer.category";
        if ($aVals = $this->request()->getArray('val')) {
            $aVals = array_merge($aVals, $this->request()->getArray('val'));
            if (Phpfox::getService('answer.category')->saveDatabase($aVals))
            {
                $this->url()->send($sLink,array(), Phpfox::getPhrase('answer.new_category_add_successfully'));
            }
        }
        else if ($aOrder = $this->request()->getArray('order'))
        {

            if (Phpfox::getService('answer.category')->updateOrder($aOrder))
            {
                $this->url()->send('admincp.answer.category', null, Phpfox::getPhrase('answer.category_order_successfully_updated'));
            }
        }
        else if ($iId = $this->request()->getInt('delete')) {
            if (Phpfox::getService('answer.category')->delete($iId)) {
                $this->url()->send($sLink,array(),Phpfox::getPhrase('answer.category_delete_successfully'));
            }
            else {
                $this->url()->send($sLink,array(),Phpfox::getPhrase('answer.category_not_found'));
            }
        }

        if ($this->request()->get('action') == 'export') {
            Phpfox::getService('answer.sample')->export();
        }
        $aConditions = array('c.parent_id = 0');

        $aCategories = Phpfox::getService('answer.category')->getListNoPage('c.*', $aConditions);
        $aCategoriesCombo = $aCategories['data'];

        $aCondition = array(

            'c.parent_id = 0'
        );
        $aCategories = Phpfox::getService('answer.category')->getListNoPage('c.*', $aCondition);
        $aCategories = $aCategories['data'];
        foreach ($aCategories as $iKey => $aVal) {
            $aCondition = array(
                'c.parent_id = ' . $aVal['id']
            );

            $aSubCategories = Phpfox::getService('answer.category')->getListNoPage('c.*', $aCondition);
            foreach ($aSubCategories['data'] as $iCount => $aSubVal) {
                $aSubCategories['data'][$iCount]['total'] = Phpfox::getService('answer.question')->countQuestion($aSubVal['id']);
            }

            $aCategories[$iKey]['child'] = $aSubCategories['data'];

            $aCategories[$iKey]['total'] = Phpfox::getService('answer.question')->countQuestion($aVal['id']);

        }

        $this->template()
            ->setTitle(Phpfox::getPhrase('answer.manager_categories'))
            ->setHeader(array(
            'admin.js' => 'module_answer',
            '<script type="text/javascript">$Core.answers.url(\'' . $this->url()->makeUrl('admincp.answer') . '\');</script>'
            ))
            ->setBreadcrumb(Phpfox::getPhrase('answer.manager_categories'))
            ->assign(array(
            'aCategoriesCombo' => $aCategoriesCombo
            ));
    }
}